package com.bw.user.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bw.core.result.ResponseResult;
import com.bw.core.utils.MD5Sign;
import com.bw.core.vo.FindOneBankResVo;
import com.bw.core.vo.FindOneOrderResVo;
import com.bw.core.vo.UserVo;
import com.bw.user.mapper.*;
import com.bw.user.pojo.*;
import com.bw.user.service.TbUserService;
import com.bw.user.vo.LoginMessage;
import com.bw.user.vo.LoginReqVo;
import com.bw.user.vo.RegisterVo;
import com.bw.user.vo.SendReqVo;
import org.apache.commons.lang.RandomStringUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author lv
 * @since 2021-03-23
 */
@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser> implements TbUserService {

    private static Logger logger = LoggerFactory.getLogger(TbUserServiceImpl.class);


    @Autowired
    private TbUserMapper usermapper;

    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private HttpServletRequest request;
   /* @Override
    public TbUser findUser(LoginReqVo login) {
        QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
        wrapper.eq("phone",login.getPhone());
        List<TbUser> tbUsers = usermapper.selectList(wrapper);
        if (tbUsers.size()>0){
            TbUser user = tbUsers.get(0);
            if (user.getPassword().equals(login.getPassword())){
                return user;
            }
            return null;
        }
        return null;
    }*/


    @Override
    public ResponseResult findUser(LoginReqVo loginReqVo) {
        TbUser user=null;
        QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
        wrapper.eq("phone",loginReqVo.getPhone());
        wrapper.eq("password",loginReqVo.getPassword());

        List<TbUser> tbUsers = usermapper.selectList(wrapper);
        if (!CollectionUtil.isEmpty(tbUsers)){
            user = tbUsers.get(0);
            String s1= MD5Sign.md5Encode(loginReqVo.getPassword());
            user.setPassword(s1);
            UUID uuid = UUID.randomUUID();
            String s = uuid.toString();
            redisTemplate.boundValueOps(s).set(JSONObject.toJSON(user).toString(),5, TimeUnit.MINUTES);
            return ResponseResult.success(user);
        }
        if (ObjectUtil.isNull(tbUsers)) {
            return ResponseResult.error("登录失败");
        }


        return null;
    }

    @Override
    public TbUser findUser(String phone) {
        QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phone);
        TbUser tbUser= new TbUser();
        wrapper.eq("password",tbUser.getPassword());

        List<TbUser> tbUsers = usermapper.selectList(wrapper);
        if (tbUsers.size() > 0) {
            TbUser user = tbUsers.get(0);

            return user;
        }

        return null;
    }

    @Override
    public ResponseResult send(SendReqVo sendReqVo) {
        Object o = redisTemplate.boundValueOps(sendReqVo.getSign()).get();


        //在redis中通过手机号获取验证码
        String yzm = RandomStringUtils.randomNumeric(6);
        System.out.println(yzm);

        redisTemplate.boundValueOps(sendReqVo.getPhone()).set(yzm, 5, TimeUnit.MINUTES);

        HashMap<String, String> map = new HashMap<>();
        map.put("phone", sendReqVo.getPhone());
        map.put("yzm", "获取的验证码为:" + yzm);

        amqpTemplate.convertAndSend("Register_size", JSONObject.toJSON(map).toString());


        if (StrUtil.hasEmpty(yzm)) {
            return ResponseResult.error("验证码超时!");
        }

        return ResponseResult.success(yzm);

    }

    @Override
    public ResponseResult loginmsg(LoginMessage loginMessage) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("phone", loginMessage.getPhone());
        TbUser tbUser = usermapper.selectOne(queryWrapper);
        if (ObjectUtil.isEmpty(tbUser)) {
            return new ResponseResult(ResponseResult.ERROR, "该用户还未注册,请先注册");
        }

        UUID uuid = UUID.randomUUID();
        String s = uuid.toString();
        redisTemplate.boundValueOps(s).set(JSONObject.toJSON(tbUser).toString(), 30, TimeUnit.DAYS);
        return new ResponseResult(ResponseResult.OK, "登录成功", s);

    }

    @Override
    public TbUser findByToken(String token) {
        String o = (String) redisTemplate.boundValueOps(token).get();
        TbUser user = JSONObject.parseObject(o, TbUser.class);
        return user;
    }



    @Override
    public ResponseResult register(RegisterVo registerVo) {

        if (StrUtil.hasEmpty(registerVo.getPhone())) {
            return ResponseResult.error("手机号不能为空");
        }
        String phone = registerVo.getPhone();
        QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phone);
        List<TbUser> tbUsers = usermapper.selectList(wrapper);

        if (CollUtil.isNotEmpty(tbUsers)) {
            return ResponseResult.error("该用户已存在");
        }
        //判断密码是否为空
        if (StrUtil.hasEmpty(registerVo.getPassword())) {
            return ResponseResult.error("密码不能为空!");
        }
        //判断验证码是否为空
        if (StrUtil.hasEmpty(registerVo.getYzm())) {
            return ResponseResult.error("验证码不能为空");
        }
        //判断确认密码是否为空
        if (StrUtil.hasEmpty(registerVo.getConfirm_password())) {
            return ResponseResult.error("确认密码不能为空");
        }

        if (registerVo.getPassword().equals(registerVo.getConfirm_password())) {
            TbUser user = new TbUser();
            BeanUtils.copyProperties(registerVo, user);
            String s1 = MD5Sign.md5Encode(registerVo.getPassword());
            user.setPassword(s1);
            user.setCreateTime(new Date());
            user.setIsdelete(0);
            user.setUpdateTime(new Date());
            user.setCreditLevel(2);
            usermapper.insert(user);
        }
        return new ResponseResult(200, "注册成功!");

    }

    @Override
    public ResponseResult updateUser(TbUser user, String newpassword) {
        user.setPassword(newpassword);
        user.setUpdateTime(new Date());

        int i = usermapper.updateById(user);
        if (i > 0) {

            return new ResponseResult(200, "修改成功!");
        }
        return new ResponseResult(201, "修改失败!");
    }

    @Override
    public ResponseResult loginpwd(LoginMessage loginMessage) {


        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("phone", loginMessage.getPhone());
        TbUser tbUser = usermapper.selectOne(queryWrapper);
        if (ObjectUtil.isNull(tbUser)) {
            return new ResponseResult(ResponseResult.ERROR, "该用户还未注册,请先注册");
        }

        UUID uuid = UUID.randomUUID();
        String s = uuid.toString();
        redisTemplate.boundValueOps(s).set(JSONObject.toJSON(tbUser).toString(), 30, TimeUnit.DAYS);
        return new ResponseResult(ResponseResult.OK, "登录成功", s);

    }

    @Override
    public ResponseResult findpwd(LoginMessage loginMessage) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("phone", loginMessage.getPhone());
        TbUser tbUser = usermapper.selectOne(queryWrapper);
        if (ObjectUtil.isNull(tbUser)) {
            return new ResponseResult(ResponseResult.ERROR, "该用户还未注册,请先注册");
        }
        UpdateWrapper<TbUser> userUpdateWrapper = new UpdateWrapper<>();
        String md5Encode = MD5Sign.md5Encode(loginMessage.getPassword());
        userUpdateWrapper.eq("phone", loginMessage.getPhone()).set("password", md5Encode);
        int update = usermapper.update(null, userUpdateWrapper);
        if (update > 0) {
            return ResponseResult.success("找回成功");
        }
        return ResponseResult.error("找回失败");
    }




    //---------风控---------风控--------风控---------风控----------

    @Autowired
    private TbCallBookAuthMapper callBookAuthMapper;

    @Autowired
    private TbLinkmanAuthMapper linkmanAuthMapper;

    @Autowired
    private TbTaobaoAuthMapper taobaoAuthMapper;

    @Autowired
    private TbOperatorAuthMapper operatorAuthMapper;

    @Override
    public UserVo findUserMessage(Long userId) {
        TbUser tbUser = usermapper.selectById(userId);
        if (ObjectUtil.isNotEmpty(tbUser)) {
            UserVo userVo = new UserVo();
            userVo.setId(tbUser.getId());
            userVo.setUsername(tbUser.getUsername());
            userVo.setPhone(tbUser.getPhone());
            userVo.setPassword(tbUser.getPassword());
            userVo.setIsIdentity(tbUser.getIsIdentity());
            userVo.setIsBankCard(tbUser.getIsBankCard());
            userVo.setIsLinkman(tbUser.getIsLinkman());
            userVo.setIsContacts(tbUser.getIsContacts());
            userVo.setIsOperator(tbUser.getIsOperator());
            userVo.setIsTaobao(tbUser.getIsTaobao());
            return userVo;
        }
        return null;
    }


    @Override
    public List<String> findLinkMan(Long userId) {
        QueryWrapper<TbLinkmanAuth> linkmanAuthQueryWrapper = Wrappers.query();
        linkmanAuthQueryWrapper.eq("userId", userId);
        List<TbLinkmanAuth> linkmanAuthList = linkmanAuthMapper.selectList(linkmanAuthQueryWrapper);
        ArrayList<String> linkManPhone = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(linkmanAuthList)) {
            TbLinkmanAuth linkmanAuth = linkmanAuthList.get(0);
            linkManPhone.add(linkmanAuth.getUrgencyLinkmanPhone());
            linkManPhone.add(linkmanAuth.getFirstLinkmanPhone());
            linkManPhone.add(linkmanAuth.getSecondLinkmanPhone());
            return linkManPhone;
        }
        return null;
    }


    @Override
    public List<String> findCallBook(Long userId) {
        QueryWrapper<TbCallBookAuth> callBookAuthQueryWrapper = Wrappers.query();
        callBookAuthQueryWrapper.eq("userId", userId);
        List<TbCallBookAuth> callBookAuthList = callBookAuthMapper.selectList(callBookAuthQueryWrapper);
        List<String> callBook = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(callBookAuthList)) {
            for (TbCallBookAuth callBookAuth : callBookAuthList) {
                callBook.add(callBookAuth.getCallBookPhone());
            }
            return callBook;
        }
        return null;
    }

    @Override
    public String findTaoBao(Long userId) {
        QueryWrapper<TbTaobaoAuth> taobaoAuthQueryWrapper = Wrappers.query();
        taobaoAuthQueryWrapper.eq("userId", userId);
        List<TbTaobaoAuth> taobaoAuthList = taobaoAuthMapper.selectList(taobaoAuthQueryWrapper);
        if (CollectionUtils.isNotEmpty(taobaoAuthList)) {
            TbTaobaoAuth taobaoAuth = taobaoAuthList.get(0);
            String taobaoData = taobaoAuth.getTaobaoData();
            return taobaoData;
        }
        return null;
    }

    @Override
    public String findOperator(Long userId) {
        QueryWrapper<TbOperatorAuth> operatorAuthQueryWrapper = Wrappers.query();
        operatorAuthQueryWrapper.eq("userId", userId);
        List<TbOperatorAuth> operatorAuthList = operatorAuthMapper.selectList(operatorAuthQueryWrapper);
        if (CollectionUtils.isNotEmpty(operatorAuthList)) {
            TbOperatorAuth operatorAuth = operatorAuthList.get(0);
            String operatorData = operatorAuth.getOperatorData();
            return operatorData;
        }
        return null;
    }


    //---------风控---------风控--------风控---------风控----------


    //汪兴达 。。。。。 查询用户信息
    @Override
    public FindOneBankResVo findBankResVo(Long userId) {

        Map<String,Object> columnMap = new HashMap<>();
        columnMap.put("user_id",userId);//写表中的列名
        List<TbUser> employees = usermapper.selectByMap(columnMap);
        if(CollectionUtil.isEmpty(employees)){
            return null;
        }

        FindOneBankResVo findOneBankResVo = new FindOneBankResVo();
        BeanUtils.copyProperties(employees.get(0),findOneBankResVo);

        return findOneBankResVo;
    }

}
